<template>
  <a-row :gutter="24">
    <a-col :md="4" :sm="24">
      <a-card :bordered="false" :loading="treeLoading">
        <a-directory-tree
          :showIcon="false"
          :treeData="treeList"
          v-if="treeList.length"
          @select="handleClick"
          :defaultExpandAll="true"
          :replaceFields="replaceFields"/>
      </a-card>
    </a-col>
    <a-col :md="19" :sm="24">
      <a-card :bordered="false">
        <div class="table-page-search-wrapper">
          <a-form layout="inline">
            <a-row :gutter="48" class="option">

              <a-col :md="6" :sm="24">
                <a-form-item label="设备名称">
                  <a-select style="width: 100%" v-model="queryParam.deviceId" allow-clear placeholder="请选择设备">
                    <a-select-option v-for="(item,index) in deviceList" :key="index" :value="item.id">{{ item.deviceName }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>

              <a-col :md="6" :sm="24">
                <span class="table-page-search-submitButtons" style="padding-left: 16px;">
                  <a-form-item label="故障类型">
                    <a-select style="width: 100%" v-model="queryParam.errorType" allow-clear placeholder="故障类型">
                      <a-select-option
                        v-for="(item,index) in errorType"
                        :key="index"
                        :value="item.code">{{ item.value }}</a-select-option>
                    </a-select>
                  </a-form-item>
                </span>
              </a-col>

              <a-col :md="6" :sm="24">
                <span class="table-page-search-submitButtons" style="padding-left: 16px;">
                  <a-form-item label="最新故障时间">
                    <a-range-picker v-model="queryDate" @change="handleChangeDate" style="width: 100%"/>
                  </a-form-item>
                </span>
              </a-col>

              <a-col :md="!advanced && 6 || 24" :sm="24">
                <span
                  class="table-page-search-submitButtons"
                  style="padding-left: 16px;"
                  :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
                  <a-button type="primary" class="btn_search_reset" @click="$refs.table.refresh()"><a-icon
                    type="search"/>查询</a-button>
                  <a-button
                    style="margin-left: 8px"
                    class="btn_search_reset"
                    @click="() => {queryDate= '';queryParam = {stationId : stationId};$refs.table.refresh()}"><a-icon
                      type="reload"/>重置</a-button>
                </span>
              </a-col>

            </a-row>
          </a-form>
        </div>

        <s-table
          ref="table"
          size="default"
          :columns="columns"
          :data="loadData"
          :alert="true"
          :rowKey="(record) => record.exceptionId"
        >
          <span slot="errorType" slot-scope="text">
            {{ errorTypeFilter(text) }}
          </span>
          <span slot="errorName" slot-scope="text,record">
            <a @click="$refs.indexForm.toIndex(record)">{{ text }}</a>
          </span>

          <span slot="status" slot-scope="text,record">
            <a-popconfirm
              placement="top"
              :title="text===0? '确定已经处理？':'确定未处理？'"
              @confirm="() => changeStatus(text,record)">
              <a>{{ statusFilter(text) }}</a>
            </a-popconfirm>
          </span>

          <span slot="action" slot-scope="text, record">
            <a-popconfirm placement="topRight" title="确认删除？" @confirm="() => del(record)">
              <a class="btn_del">删除</a>
            </a-popconfirm>
          </span>
        </s-table>

        <add-form ref="addForm" @ok="handleOk"/>
        <edit-form ref="editForm" @ok="handleOk"/>
        <index-form ref="indexForm" @ok="handleOk"/>
      </a-card>
    </a-col>
  </a-row>
</template>

<script>
  import { STable } from '@/components'
  import { exceptionChangeStatus, page, del } from '@/api/modular/main/bizexception/bizExceptionManage'
  import addForm from './addForm'
  import editForm from './editForm'
  import indexForm from './bizexceptionlog/index'
  import { treeList } from '@/api/modular/main/bizstation/bizStationManage'
  import { deviceList } from '@/api/modular/main/bizdevice/bizDeviceManage'
  import { gatewayList } from '@/api/modular/main/bizgateway/bizGatewayManage'

  export default {
    components: {
      STable,
      addForm,
      editForm,
      indexForm
    },

    data () {
      return {
        data: [],
        page: {},
        loading: false,
        advanced: false, // 高级搜索 展开/关闭
        queryParam: {}, // 查询参数
        queryParam1: {}, // 查询参数,
        queryDate: [],
        stationId: 0,
        columns: [ // 表头
          {
            title: '设备名称',
            dataIndex: 'deviceName',
            width: 300
          },
          {
            title: '故障名称',
            dataIndex: 'errorName',
            scopedSlots: { customRender: 'errorName' }
          },
          {
            title: '最新故障时间',
            dataIndex: 'newExceptionTime',
            align: 'center'
          },
          {
            title: '故障类型',
            dataIndex: 'errorType',
            scopedSlots: { customRender: 'errorType' }
          },
          {
            title: '网关名称',
            dataIndex: 'gatewayName'
          },
          {
            title: '处理状态',
            dataIndex: 'status',
            scopedSlots: { customRender: 'status' }
          },
          {
            title: '数量',
            dataIndex: 'errorCount'
          },
          {
            title: '操作',
            dataIndex: 'action',
            scopedSlots: { customRender: 'action' },
            align: 'center'
          }
        ],
        errorType: [
          { code: 0, value: '未知' },
          { code: 1, value: '已知' }
        ],
        // 加载数据方法 必须为 Promise 对象
        loadData: parameter => {
          return page(Object.assign(parameter, this.queryParam)).then((res) => {
            return res.data
          })
        },
        selectedRowKeys: [],
        selectedRows: [],
        defaultExpandedKeys: [],
        replaceFields: {
          key: 'id'
        },
        treeList: [],
        treeLoading: true,
        deviceList: [],
        deviceIds: [],
        stationTreeIndex: -1,
        gatewayList: []
      }
    },
    created () {
      this.getStationTree()
    },
    methods: {
      // 改变时间事件
      handleChangeDate (date, dateString) {
        this.queryParam.startTime = dateString[0]
        this.queryParam.endTime = dateString[1]
      },
      del (record) {
        del({ id: record.exceptionId }).then((res) => {
          if (res.success) {
            this.$message.success('删除成功')
            this.$refs.table.refresh()
          } else {
            this.$message.error('删除失败：' + res.message)
          }
        }).catch((err) => {
          this.$message.error('删除错误：' + err.message)
        })
      },
      getGatewayList (stationId) {
        gatewayList({ stationId: stationId }).then(res => {
          if (res.success) {
            this.gatewayList = res.data
            this.gatewayIds = []
            this.gatewayList.filter(value => {
              this.gatewayIds.push(value.id)
            })
            this.handleOk()
          }
        })
      },
      toggleAdvanced () {
        this.advanced = !this.advanced
      },
      handleOk () {
        this.$refs.table.refresh()
      },
      onSelectChange (selectedRowKeys, selectedRows) {
        this.selectedRowKeys = selectedRowKeys
        this.selectedRows = selectedRows
      },
      getStationTree () {
        treeList(Object.assign(this.queryParam)).then(res => {
          this.treeLoading = false
          if (!res.success) {
            return
          }
          this.treeList = res.data
        })
      },
      handleClick (e) {
        if (e.length > 0) {
          this.queryParam = { stationId: e.toString() }
          this.stationId = e.toString()
          this.$refs.table.refresh()
          const param = {
            stationId: e.toString()
          }
          this.getGatewayList(e.toString())
          deviceList(param).then(res => {
            this.deviceIds = []
            this.deviceList = res.data
            for (let i = 0; i < res.data.length; i++) {
              this.deviceIds.push(res.data[i].id)
            }
          })
        } else {
          this.queryParam.deviceIds = ''
          this.$refs.table.refresh()
        }
      },
      /**
       * 修改用户状态
       */
      changeStatus (code, record) {
        if (code === 0) {
          this.status = 1
        } else if (code === 1) {
          this.status = 0
        }
        exceptionChangeStatus({ id: record.exceptionId, status: this.status }).then(res => {
          if (res.success) {
            this.$message.success('操作成功')
            this.$refs.table.refresh()
          } else {
            this.$message.error('操作失败：' + res.message)
          }
        })
      },
      statusFilter (status) {
        if (status === 0) {
          return '未处理'
        } else if (status === 1) {
          return '已处理'
        } else {
          return '未处理'
        }
      },
      errorTypeFilter (text) {
        if (text === 0) {
          return '未知故障'
        } else if (text === 1) {
          return '已知故障'
        }
      }
    }
  }
</script>

<style lang="less" scoped>
  @import '../../../assets/css/list.less';

  .table-operator {
    margin-bottom: 18px;
  }

  .table-page-search-wrapper {
    padding-left: 10px;

    /deep/ .ant-row {
      margin-left: 0 !important;
    }
  }

  button {
    margin-right: 8px;
  }

  @media (max-width: 1680px) {
    .option {
      transform: scale(0.9) translateX(-120px);
    }
  }

  @media (max-width: 1280px) {
    .option {
      transform: scale(0.8) translateX(-160px);
    }
  }
</style>
